
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[EBAS_SP_HENT_FAG]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[EBAS_SP_HENT_FAG]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [DBO].[EBAS_SP_HENT_FAG] 
	@session varchar(255),
	@navn varchar(255) = NULL,
	@gruppeGuid varchar(255) = NULL
WITH ENCRYPTION
AS
	DECLARE @rettighed int,
		@antal int, 
		@guid uniqueidentifier
	
	SET NOCOUNT ON
	SET @antal = 0

	CREATE TABLE #temp ( rett int )
	INSERT INTO #temp (rett)
	EXEC EBAS.DBO.EBAS_SP_SIKKERHED_VERIFICER_SESSION @session	

	SET @rettighed = (SELECT IsNull(MAX(rett),0) FROM #temp)
	
	IF 0 < @rettighed 
	BEGIN
		SET @antal = (SELECT COUNT(*) FROM EBAS_FAG)
		
		IF @navn IS NULL AND @gruppeGuid IS NULL
			SELECT 	F.GUID AS GUID, F.NAVN, F.BOGPAKKE_GUID, 
				F.KARAKTER_SKALA_GUID, S.NAVN AS KARAKTER_SKALA,
				@antal AS ANTAL
			FROM 	EBAS_FAG F, EBAS_KARAKTER_SKALA S
			WHERE 	F.KARAKTER_SKALA_GUID = S.GUID	
		ELSE IF @navn IS NOT NULL AND @gruppeGuid IS NULL
			SELECT 	F.GUID AS GUID, F.NAVN, F.BOGPAKKE_GUID, 
				F.KARAKTER_SKALA_GUID, S.NAVN AS KARAKTER_SKALA,
				@antal AS ANTAL
			FROM 	EBAS_FAG F, EBAS_KARAKTER_SKALA S
			WHERE 	F.KARAKTER_SKALA_GUID = S.GUID	
			AND	F.NAVN = @navn
		ELSE IF @gruppeGuid IS NOT NULL
			SELECT 	F.GUID AS GUID, F.NAVN, F.BOGPAKKE_GUID, 
				F.KARAKTER_SKALA_GUID, S.NAVN AS KARAKTER_SKALA,
				@antal AS ANTAL
			FROM 	EBAS_FAG F, EBAS_KARAKTER_SKALA S
			WHERE 	F.KARAKTER_SKALA_GUID = S.GUID	
			AND	F.GUID IN (
				SELECT FAG_GUID
				FROM EBAS_GRUPPE_FAG
				WHERE GRUPPE_GUID = @gruppeGuid
			)
	END
	ELSE			
		SELECT 	F.GUID AS NAVN, F.NAVN, F.BOGPAKKE_GUID, 
			F.KARAKTER_SKALA_GUID, S.NAVN AS KARAKTER_SKALA,
			0 AS ANTAL
		FROM 	EBAS_FAG F, EBAS_KARAKTER_SKALA S
		WHERE 	F.KARAKTER_SKALA_GUID = S.GUID
		AND 	F.GUID IS NULL
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
